package com.voicechat.firstmet.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.CustomListener;
import com.bigkoo.pickerview.listener.OnOptionsSelectChangeListener;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.bigkoo.pickerview.view.TimePickerView;
import com.contrarywind.view.WheelView;
import com.google.gson.Gson;
import com.voicechat.firstmet.App;
import com.voicechat.firstmet.MainActivity;
import com.voicechat.firstmet.R;
import com.voicechat.firstmet.base.BaseActivity;
import com.voicechat.firstmet.bean.JsonBean;
import com.voicechat.firstmet.bean.MySelfInfoBean;
import com.voicechat.firstmet.client.OssClient;
import com.voicechat.firstmet.client.OssConfig;
import com.voicechat.firstmet.net.HTTPAPI;
import com.voicechat.firstmet.net.Params;
import com.voicechat.firstmet.net.service.MeInfoService;
import com.voicechat.firstmet.utils.ConstantSet;
import com.voicechat.firstmet.utils.ConstellationUtils;
import com.voicechat.firstmet.utils.GlideLoadUtils;
import com.voicechat.firstmet.utils.ParcelableUtils;
import com.voicechat.firstmet.utils.PhoneUtils;
import com.voicechat.firstmet.utils.PopUtils;
import com.voicechat.firstmet.utils.SDCardUtils;
import com.voicechat.firstmet.utils.SPUtils;
import com.voicechat.firstmet.utils.StatusBarUtils;
import com.voicechat.firstmet.utils.ThreadManager;
import com.voicechat.firstmet.utils.Utils;
import com.voicechat.firstmet.view.CircleImageView;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.voicechat.firstmet.utils.PopUtils.hidePopupWindow;

/**
 * @ProjectName: FirstMet
 * @Package: com.voicechat.firstmet.activity_imessage
 * @ClassName: PersonDataSetActivity
 * @Description: 个人资料设置
 * @Author: ljp
 * @CreateDate: 2018/9/27 9:23
 * @Version: 1.0
 */
public class PersonDataSetActivity extends BaseActivity {
    @BindView(R.id.linear_back)
    LinearLayout linearBack;
    @BindView(R.id.tv_save)
    TextView tvSave;
    @BindView(R.id.image_icon)
    CircleImageView imageIcon;
    @BindView(R.id.et_nikName)
    EditText etNikName;
    @BindView(R.id.et_sign)
    EditText etSign;
    @BindView(R.id.tv_sex)
    TextView tvSex;
    @BindView(R.id.tv_birthday)
    TextView tvBirthday;
    @BindView(R.id.tv_place)
    TextView tvPlace;
    @BindView(R.id.tv_height)
    TextView tvHeight;
    @BindView(R.id.tv_voice)
    TextView tvVoice;
    @BindView(R.id.voice_time)
    TextView voiceTime;
    @BindView(R.id.linear_voice)
    LinearLayout linearVoice;
    @BindView(R.id.rela_vioce)
    RelativeLayout relaVioce;
    private TimePickerView pvCustomLunar;
    private String TAG = "PersonDataSetActivity";
    //城市数据list
    private ArrayList<JsonBean.DataBean> options1Items;
    private ArrayList<ArrayList<String>> options2Items;
    private OptionsPickerView pvNoLinkOptions;
    //身高和体重数据list
    private ArrayList<String> statureList;
    private ArrayList<String> weightList;
    private Bitmap photo;
    //上传照片返回的oss地址
    private String picture;
    //语音介绍
    private String ossVoiceUrl;
    private String voiceName;//语音介绍地址
    private String newVoiceName;//语音介绍地址
    private MySelfInfoBean.ObjectBean mySeleInfo;
    private String province;//省
    private String city;//市
    //获取星座
    String constellation;
    //获取生日
    String birthday;
    private String height;//身高体重
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 1) {
                Bundle data = msg.getData();
                byte[] bitmap = data.getByteArray("bitmap");
                GlideLoadUtils.getInstance().glideLoad(App.getContext(),bitmap,imageIcon);
            }else if(msg.what == 2){
                // Log.i(TAG, "initView: ----+"+player.getTime(new File(voice)));
                Log.i(TAG, "initView: ---voice-+"+voiceName);
                if (TextUtils.isEmpty(newVoiceName)) {
                   // voiceTime.setText(MediaUtil.getInstance().getDuration(voiceName)/1000 + "”");
                }
            }
        }
    };
    private Runnable runnable;
    private int duration = 0;

    @Override
    protected int setStatusBarColor() {
        return 0;
    }

    @Override
    protected boolean isSettingStatusBarText() {
        return false;
    }

    @Override
    protected int loadLayout() {
        return R.layout.activity_person_dataset;
    }

    @Override
    protected void initLayout(Bundle savedInstanceState) {
        ButterKnife.bind(this);
        //透明状态栏
        StatusBarUtils.Full(this);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            this.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        }
        mySeleInfo = MySelfInfoBean.ObjectBean.CREATOR.createFromParcel(ParcelableUtils.unmarshall(
                SPUtils.getEditoString(SPUtils.SP_MYSELFINFO)));
        initView();
    }
    /**
     * 数据实例化
     */
    private void initView() {
        initLunarPicker();
        initJsonData();
        initStatue();
        initNoLinkOptionsPicker();
        setImage(mySeleInfo.getAvatarUrl());
        etNikName.setText(mySeleInfo.getNickName());
        if (mySeleInfo.getGender() == 1) {//性别  1男2女
            tvSex.setText("男");
        } else {
            tvSex.setText("女");
        }
        etSign.setText(mySeleInfo.getAutograph());
        if (!TextUtils.isEmpty(mySeleInfo.getBirthday())) {
            Log.i(TAG, "initView: -----"+mySeleInfo.getBirthday());
            tvBirthday.setText(Utils.getAge(mySeleInfo.getBirthday())+"  "+mySeleInfo.getConstellation());
        }
        if(!TextUtils.isEmpty(mySeleInfo.getAscription())){
            tvPlace.setText(mySeleInfo.getAscription());
        }
        if(!TextUtils.isEmpty(mySeleInfo.getHeight())){
            tvHeight.setText(mySeleInfo.getHeight());
        }
        if(!TextUtils.isEmpty(mySeleInfo.getVoiceInfo())){
            linearVoice.setVisibility(View.VISIBLE);
            tvVoice.setVisibility(View.GONE);
            voiceTime.setText(mySeleInfo.getDuration()+ "”");
        }
    }
    @Override
    protected void onStart() {
        super.onStart();
        setThread();
    }
    /**
     * @return
     * @method
     * @description 启动线程池下载语音介绍信息
     * @date: 2018/10/16 14:30
     * @author: ljp
     */
    private void setThread() {
        ThreadManager.getThreadPool().execute(runnable = new Runnable() {
            @Override
            public void run() {
                    String voiceInfo = mySeleInfo.getVoiceInfo();
                    OssClient.getInstance().init(context).fileDownload(voiceInfo, new OssClient.OnDownloadFile() {
                        @Override
                        public void onDownFileSuccess(InputStream inputStream) {
                            String voice = Utils.getVoiceName(voiceInfo);
                            //Log.i(TAG, "onDownFileSuccess: ---------"+voiceName);
                            String path = ConstantSet.VOICE;
                            try {
                                OssConfig.writeToLocal(path,inputStream,voice);
                                voiceName = ConstantSet.VOICE +ConstantSet.VOICEINTR_PATH+Utils.getVoiceName(mySeleInfo.getVoiceInfo());
                                //Message message = Message.obtain();
                                //message.what = 2;
                                //handler.sendMessage(message);
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                        @Override
                        public void onDownFileProgress(String progress) {
                            //Log.i(TAG, "onDownFileProgress: ----------"+progress);
                        }
                    });
            }
        });
    }
    /**
     * @return
     * @method
     * @description 获取头像
     * @date: 2018/10/19 17:21
     * @author: ljp
     */
    private void setImage(String url) {
        Log.i(TAG, "setImage: --------"+url);
        new Thread(new Runnable() {
            @Override
            public void run() {
                OssClient.getInstance().init(context).fileDownload(url, new OssClient.OnDownloadFile() {
                    @Override
                    public void onDownFileSuccess(InputStream inputStream) {
                        //Log.i(TAG, "onDownFileSuccess: ----------"+inputStream);
                        byte[] bitmap = null;
                        try {
                            bitmap = OssConfig.readInputStreamToByte(inputStream);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        //if(view.getTag() != null && view.getTag().equals(url)) {
                        Message message = Message.obtain();
                        message.what = 1;
                        Bundle bundle = new Bundle();
                        //bundle.putString("tag",url);
                        bundle.putByteArray("bitmap", bitmap);
                        message.setData(bundle);
                        handler.sendMessage(message);
                        //  }
                    }

                    @Override
                    public void onDownFileProgress(String progress) {

                    }
                });
            }
        }).start();

    }
    @OnClick({R.id.linear_back, R.id.tv_save, R.id.image_icon, R.id.tv_birthday,
            R.id.tv_place, R.id.tv_height,  R.id.voice_time, R.id.linear_voice, R.id.rela_vioce})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.linear_back:
                finish();
                break;
            case R.id.tv_save:
                httpData();
                break;
            case R.id.image_icon:
                setPopuWindow();
                break;
                //出生日期
            case R.id.tv_birthday:
                pvCustomLunar.show();
                break;
                //城市选择
            case R.id.tv_place:
                showPickerView();
                break;
                //身高体重选择
            case R.id.tv_height:
                pvNoLinkOptions.show();
                break;
            case R.id.voice_time:
                break;
            case R.id.linear_voice:
                break;
            //选择设置语音介绍
            case R.id.rela_vioce:
                Intent intent = new Intent(activity, SetVoiceIntroduceActivity.class);
                startActivityForResult(intent,10000);
                break;
        }
    }

    private void httpData() {
        String mobile = SPUtils.getEditoString(SPUtils.SP_PHONE);
        String token = SPUtils.getEditoString(SPUtils.SP_TOKEN);
        String deviceInfo = PhoneUtils.getDeviceInfo(context);
        Params params = new Params();
        params.put("id", mySeleInfo.getId());
        params.put("mobile", mobile);//手机号码
        params.put("token", token);//token
        params.put("equipmentId",deviceInfo);//设备号
        if(!TextUtils.isEmpty(picture)){
            params.put("avatarUrl",Utils.spitString(picture));//头像地址
        }
        if(!etNikName.getText().toString().trim().equals(mySeleInfo.getNickName())){
            params.put("nickName",etNikName.getText().toString().trim());//昵称
        }
        if(!TextUtils.isEmpty(birthday) && !birthday.equals(mySeleInfo.getBirthday())){
                params.put("birthday", birthday);//出生日期
        }
        if(!TextUtils.isEmpty(constellation) && !constellation.equals(mySeleInfo.getBirthday())){
            params.put("constellation",constellation);//星座
        }
        if(!etSign.getText().toString().trim().equals(mySeleInfo.getAutograph())){
            params.put("autograph",etSign.getText().toString().trim());//签名
        }
        if(!TextUtils.isEmpty(province) &&!province.trim().equals(mySeleInfo.getAscription())){
            params.put("ascription",city);//所在地
            params.put("province",province);//所在地
        }
        if(!TextUtils.isEmpty(height) &&!height.equals(mySeleInfo.getAscription())){
            params.put("height",height);//身高,体重
        }
        if(!TextUtils.isEmpty(ossVoiceUrl)){
            params.put("voiceInfo",ossVoiceUrl);//语音地址
        }
        if(duration != 0){
            params.put("duration",duration);//语音地址
        }
        MeInfoService.updateData(params).subscribe(mySelfInfoBean -> {
           // Log.i(TAG, "httpData: -----"+mySelfInfoBean.getCode()+"-----"+mySelfInfoBean.getMsg());
           //Log.i(TAG, "httpData: -----"+mySelfInfoBean.getObject().toString());
            if(mySelfInfoBean.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETRUN_SUCCESS){
                SPUtils.setEditorKeyValue(SPUtils.SP_MYSELFINFO, ParcelableUtils.marshall(mySelfInfoBean.getObject()));
                Intent intent = new Intent(activity, MainActivity.class);
                intent.putExtra("flag",4);
                startActivity(intent);
            }else if (mySelfInfoBean.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETURN_NO_TOKEN){
                toast_MakeText(getResources().getString(R.string.token));
                Utils.setToken(context);
            }else {
                toast_MakeText(mySelfInfoBean.getMsg());
            }
        },throwable -> {
            Log.i(TAG, "httpData: ----"+throwable.toString());
            toast_MakeText(getResources().getString(R.string.net_error));
        });
    }
    private String getTime(Date date) {//可根据需要自行截取数据显示
        // Log.d("getTime()", "choice date millis: " + date.getTime());
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        return format.format(date);
    }
    /**
     * @return
     * @method
     * @description 日期选择框
     * @date: 2018/8/31 16:58
     * @author: ljp
     */
    private void initLunarPicker() {
        Calendar selectedDate = Calendar.getInstance();//系统当前时间
        Calendar startDate = Calendar.getInstance();
        startDate.set(1950, 1, 23);
        Calendar endDate = Calendar.getInstance();
        Calendar cd = Calendar.getInstance();
        endDate.set(cd.get(Calendar.YEAR), cd.get(Calendar.MONTH), cd.get(Calendar.DATE));
        //时间选择器 ，自定义布局
        pvCustomLunar = new TimePickerBuilder(this, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                String substring = Utils.dateToString(date,"yyyy-MM-dd").substring(0, 4);
                String time = getTime(new Date());
                String substring2 = time.substring(0, 4);
                int year = (Integer.parseInt(substring2)) - (Integer.parseInt(substring));
                if (year == 0 || year < 18) {
                    toast_MakeText("您还未成年");
                    return;
                } else {
                    birthday = Utils.dateToString(date,"yyyy-MM-dd");
                }
                SimpleDateFormat format3 = new SimpleDateFormat("yyyy");
                SimpleDateFormat format = new SimpleDateFormat("MM");
                SimpleDateFormat format2 = new SimpleDateFormat("dd");
                String moth;
                if (format.format(date).substring(0, 1).equals("0")) {
                    moth = format.format(date).substring(1, 2);
                } else {
                    moth = format.format(date);
                }
                String day = format2.format(date);
                String nowDate = format3.format(new Date());
                String birthDate = format3.format(date);
                //获取星座
                constellation = ConstellationUtils.getConstellation(Integer.parseInt(moth), Integer.parseInt(day));
                //得到年龄
                int age = Integer.parseInt(nowDate) - Integer.parseInt(birthDate);
                //if (age >= 18) {
                    tvBirthday.setText(age + "   " + constellation);
                //}
                // Toast.makeText(RegisterActivity.this, getTime(date), Toast.LENGTH_SHORT).show();
            }
        })
                .setDate(selectedDate)
                .setRangDate(startDate, endDate)
                .setLayoutRes(R.layout.pickerview_custom_lunar, new CustomListener() {
                    @Override
                    public void customLayout(final View v) {
                        final TextView tvSubmit = (TextView) v.findViewById(R.id.tv_finish);
                        TextView ivCancel = (TextView) v.findViewById(R.id.iv_cancel);
                        WheelView viewById = (WheelView) v.findViewById(R.id.year);
                        viewById.setTextSize(32.0f);
                        tvSubmit.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pvCustomLunar.returnData();
                                pvCustomLunar.dismiss();
                            }
                        });
                        ivCancel.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pvCustomLunar.dismiss();
                            }
                        });
                    }
                })
                .setType(new boolean[]{true, true, true, false, false, false})
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .setDividerColor(Color.parseColor("#FF3B5E"))
                .build();
    }

    /**
     * @return
     * @method
     * @description 城市选择器
     * @date: 2018/9/27 11:46
     * @author: ljp
     */
    private void showPickerView() {// 弹出选择器
        OptionsPickerView pvOptions = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                String tx = options1Items.get(options1).getPickerViewText() +
                        options2Items.get(options1).get(options2) /*+
                        options3Items.get(options1).get(options2).get(options3)*/;
                // Toast.makeText(JsonDataActivity.this, tx, Toast.LENGTH_SHORT).show();
                province = options1Items.get(options1).getPickerViewText();
                city = options2Items.get(options1).get(options2);
                tvPlace.setText(tx);
            }
        })
                .setTitleText("城市选择")
                .setDividerColor(Color.parseColor("#FF3B5E"))
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(20)
                .build();

        /*pvOptions.setPicker(options1Items);//一级选择器*/
        pvOptions.setPicker(options1Items, options2Items);//二级选择器
        // pvOptions.setPicker(options1Items, options2Items, options3Items);//三级选择器
        pvOptions.show();
    }

    /**
     * @return
     * @method
     * @description 身高体重选择器
     * @date: 2018/9/27 11:54
     * @author: ljp
     */
    private void initNoLinkOptionsPicker() {// 不联动的多级选项
        pvNoLinkOptions = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                String str = statureList.get(options1) + "   " + weightList.get(options2);
                height = statureList.get(options1) + ";" + weightList.get(options2);
                tvHeight.setText(str);
            }
        })
                .setOptionsSelectChangeListener(new OnOptionsSelectChangeListener() {
                    @Override
                    public void onOptionsSelectChanged(int options1, int options2, int options3) {
                    }
                })
                .setTitleText("身高体重选择")
                .setDividerColor(Color.parseColor("#FF3B5E"))
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(20)
                .build();
        pvNoLinkOptions.setNPicker(statureList, weightList, null);
        pvNoLinkOptions.setSelectOptions(0, 1, 1);
    }

    /**
     * @return
     * @method
     * @description 身高体重数据
     * @date: 2018/9/27 13:39
     * @author: ljp
     */
    private void initStatue() {
        statureList = new ArrayList<>();
        weightList = new ArrayList<>();
        for (int i = 150; i <= 190; i++) {
            statureList.add(i + "cm"); // height: 150-180
        }
        for (int i = 30; i <= 150; i++) {
            weightList.add(i + "kg"); // weight: 30.0-150.0
        }
    }

    /**
     * @return
     * @method
     * @description 城市数据解析
     * @date: 2018/9/27 11:22
     * @author: ljp
     */
    private void initJsonData() {//解析数据
        options1Items = new ArrayList<>();
        options2Items = new ArrayList<>();
        /**
         * 注意：assets 目录下的Json文件仅供参考，实际使用可自行替换文件
         * 关键逻辑在于循环体
         * */
        String JsonData = Utils.getJson(this, "city.json");//获取assets目录下的json文件数据
        ArrayList<JsonBean.DataBean> jsonBean = parseData(JsonData);//用Gson 转成实体
        /**
         * 添加省份数据
         *
         * 注意：如果是添加的JavaBean实体，则实体类需要实现 IPickerViewData 接口，
         * PickerView会通过getPickerViewText方法获取字符串显示出来。
         */
        options1Items = jsonBean;
        for (int i = 0; i < jsonBean.size(); i++) {//遍历省份
            ArrayList<String> cityList = new ArrayList<>();//该省的城市列表（第二级）
            ArrayList<String> provinceList = new ArrayList<>();//该省的城市列表（第二级）
            String provinceName = jsonBean.get(i).getName();
            provinceList.add(provinceName);//添加城市
            for (int c = 0; c < jsonBean.get(i).getCities().size(); c++) {//遍历该省份的所有城市
                String cityName = jsonBean.get(i).getCities().get(c);
                cityList.add(cityName);//添加城市
            }
            /**
             * 添加城市数据
             */
            options2Items.add(cityList);
        }
    }
    /**
     * @return
     * @method
     * @description 头像
     * @date: 2018/8/31 11:30
     * @author: ljp
     */
    public void setPopuWindow() {
        View view = View.inflate(this, R.layout.pop_repl_picture, null);
        PopUtils.showPopupWindow(this, view, false);
        //实例化控件
        TextView tvPhotoAlbum = view.findViewById(R.id.tv_photo_album);
        TextView tvPhotograph = (TextView) view.findViewById(R.id.tv_photograph);
        TextView tv_cancel = (TextView) view.findViewById(R.id.tv_cancel);
        file = new File(IMAGE_FILE_LOCATION);
        if (!file.exists()) {
            SDCardUtils.makeRootDirectory(IMAGE_FILE_LOCATION);
        }
        file = new File(IMAGE_FILE_LOCATION + ConstantSet.USERTEMPPIC);
        imageUri = Uri.fromFile(file);//The Uri t
        //取消
        tv_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                hidePopupWindow();
            }
        });
        tvPhotograph.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //拍照
                if (Build.VERSION.SDK_INT >= 23) {
                    int checkCallPhonePermission = ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA);
                    if (checkCallPhonePermission != PackageManager.PERMISSION_GRANTED) {
                        ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.CAMERA}, 222);
                        return;
                    } else {
                        openCamra();//调用具体方法
                    }
                } else {
                    openCamra();//调用具体方法
                }
            }
        });
        //相册
        tvPhotoAlbum.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //拍照
                if (Build.VERSION.SDK_INT >= 23) {
                    int checkCallPhonePermission = ContextCompat.checkSelfPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE);
                    if (checkCallPhonePermission != PackageManager.PERMISSION_GRANTED) {
                        ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 223);
                        return;
                    } else {
                        openIcon();//调用具体方法
                    }
                } else {
                    openIcon();//调用具体方法
                }
            }
        });

    }
    /**
     * 裁剪的图片的uri
     */
    private Uri uritempFile = null;
    File file;
    Uri imageUri;
    private static final String IMAGE_FILE_LOCATION = ConstantSet.LOCALFILE;//temp file
    /**
     * @return
     * @method
     * @description 打开相机
     * @date: 2018/8/31 11:45
     * @author: ljp
     */
    private void openCamra() {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);//action is capture
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        startActivityForResult(intent, ConstantSet.TAKEPICTURE);//or TAKE_SMALL_PICTURE
        hidePopupWindow();
    }
    /**
     * @method
     * @description 选择相册
     * @date: 2018/8/31 14:54
     * @author: ljp
     * @return
     */
    private void openIcon() {
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setType("image/*");
        startActivityForResult(intent, ConstantSet.SELECTPICTURE);
        hidePopupWindow();
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != RESULT_OK) {
            return;
        }
        switch (requestCode) {
            //拍照设置头像
            case ConstantSet.TAKEPICTURE:
                Intent tcutIntent = new Intent(context, ClippingPageActivity.class);
                tcutIntent.putExtra("type", "takePicture");
                startActivityForResult(tcutIntent, ConstantSet.CROPPICTURE);
                break;
                //选择照片
            case ConstantSet.SELECTPICTURE:
                if (data != null) {
                    String imagePath;
                    Uri uri = data.getData();
                    if (uri != null) {
                        if (!TextUtils.isEmpty(uri.getAuthority())) {
                            Cursor cursor = getContentResolver().query(uri,
                                    new String[]{MediaStore.Images.Media.DATA}, null, null, null);
                            if (null == cursor) {
                                Toast.makeText(this, "图片没找到", Toast.LENGTH_SHORT).show();
                                return;
                            }
                            cursor.moveToFirst();
                            imagePath = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
                            cursor.close();
                        } else {
                            imagePath = uri.getPath();
                        }
                        // Log.i(TAG, "onActivityResult: -------File-imagePath----"+ FileSizeUtil.getAutoFileOrFilesSize(imagePath));
                        Intent scutIntent = new Intent(context, ClippingPageActivity.class);
                        scutIntent.putExtra("type", "selectPicture");
                        scutIntent.putExtra("path", imagePath);
                        startActivityForResult(scutIntent, ConstantSet.CROPPICTURE);
                    } else {
                        Toast.makeText(this, "图片没找到", Toast.LENGTH_SHORT).show();
                        return;
                    }
                }
                break;
                //裁剪返回照片
            case ConstantSet.CROPPICTURE:
                File fileImager = new File(ConstantSet.LOCALFILE + ConstantSet.USERINFO);
                if (fileImager != null && fileImager.length() != 0) {
                    uritempFile = Uri.fromFile(fileImager);
                }
                try {
                    if (uritempFile != null) {
                        photo = BitmapFactory.decodeStream(activity.getContentResolver().openInputStream(uritempFile));
                        imageIcon.setImageBitmap(photo); //把图片显示在ImageView控件上
                       // Log.i(TAG,"new/"+"第个图片的大小为：----uritempFile----"+new File(uritempFile.getPath()).length()/1024+"KB");
                        setOssImage(uritempFile.getPath());
                    } else {
                        Toast.makeText(this, "图片没找到", Toast.LENGTH_SHORT).show();
                    }
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
                break;
                //保存语音返回url
            case 10000:
                if(data != null){
                    ossVoiceUrl = data.getStringExtra("ossVoiceUrl");
                    String time = data.getStringExtra("time");
                    newVoiceName = data.getStringExtra("voiceName");
                    Log.i(TAG, "onActivityResult: ---ossVoiceUrl--"+ossVoiceUrl+"--time--"+time);
                    Log.i(TAG, "onActivityResult: ---voiceName--"+voiceName);
                    duration = Integer.parseInt(time);
                    voiceTime.setText(time + "”");
                    linearVoice.setVisibility(View.VISIBLE);
                    tvVoice.setVisibility(View.GONE);
                }
                break;
        }

    }
    /**
     * @method
     * @description 上传图片到oss服务器
     * @date: 2018/9/25 15:54
     * @author: ljp
     * @return
     */
    private void setOssImage(String image){
        String mobile = SPUtils.getEditoString(SPUtils.SP_PHONE);
        String name = Utils.getMobile(mobile) + System.currentTimeMillis();
        new Thread(new Runnable() {
            @Override
            public void run() {
                OssClient.getInstance().init(context).
                        upload(name, image, OssConfig.HEAD, new OssClient.OnUploadFile() {
                            @Override
                            public void onUploadFileSuccess(String info) {
                                picture = info;
                                //Log.i(TAG, "onUploadFileSuccess: --image---"+info);
                            }
                            @Override
                            public void onUploadFileFailed(String errCode) {

                            }
                        });
            }
        }).start();
    }
    /**
     * @return
     * @method
     * @description //Gson 解析
     * @date: 2018/9/27 11:23
     * @author: ljp
     */
    public ArrayList<JsonBean.DataBean> parseData(String result) {
        ArrayList<JsonBean.DataBean> detail = new ArrayList<>();
        try {
            JSONObject jsonObject = new JSONObject(result);
            JSONArray data = jsonObject.getJSONArray("data");
            Gson gson = new Gson();
            for (int i = 0; i < data.length(); i++) {
                JsonBean.DataBean entity = gson.fromJson(data.optJSONObject(i).toString(), JsonBean.DataBean.class);
                detail.add(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return detail;
    }
}
